import { Component, ViewChild } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { DValidateRules, DialogService, FormLayout, TableWidthConfig } from 'ng-devui';
import { DeviceService } from 'src/app/@core/services/device.ts/device.service';
import { EncodeRulesService } from 'src/app/@core/services/encoderRule/encode-rules.service';
import { ProcessService } from 'src/app/@core/services/process/process.service';
import { UserService } from 'src/app/@core/services/user/user.service';
import { AttachmentComponent } from 'src/app/@shared/components/attachment/attachment.component';
import { SeleceDeviceComponent } from 'src/app/@shared/components/selece-device/selece-device.component';
import { SelectUserComponent } from 'src/app/@shared/components/select-user/select-user.component';

@Component({
  selector: 'app-edit-process',
  templateUrl: './edit-process.component.html',
  styleUrls: ['./edit-process.component.scss']
})
export class EditProcessComponent {
  user:any;
  device:any
  tabActiveId: string | number = '基本信息';
  tableData = [
    {
      id:null,
      employeeCode:null,
      name:null,
      ownerPhoneNumber:null,
      departmentName:null,
    }
  ]
  deviceData =[
    {
      id:null,
      equipmentName:null,
      equipmentNum:null,
    }
  ]
  Process={
    processNum: "",
    processName: "",
    processNote: "",
    attachmentUrl: "",
    processUserIds: [
      null
    ],
    processEquipmentIds: [
      null
    ]
  }
  ProcessRules:{[key:string]:DValidateRules}={
    processNum: {
      messageShowType:'text',
      validators: [
        { required: true,message: '工序编码不能为空' },
        { minlength: 2, message: '*工序编码长度至少为2' },
        { maxlength: 40, message: '*工序编码长度至多为40' },
        { pattern: /^[^\s]*$/, message: '*工序编码不能包含空格' }
      ]
    },
    processName: {
      messageShowType:'text',
      validators: [
        { required: true,message: '工序名称不能为空' },
        { minlength: 2, message: '*工序名称长度至少为2' },
        { maxlength: 40, message: '*工序名称长度至多为40' },
        { pattern: /^[^\s]*$/, message: '*工序名称不能包含空格' }
      ]
    },
  }
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '50px'
    },
    {
      field:'caozuo',
      width:'150px'
    },
    {
      field: 'showType',
      width: '150px'
    },
    {
      field: 'showType',
      width: '150px'
    },
    {
      field: 'enabled',
      width: '150px'
    }
  ];//表格宽度配置
  devuiTableWidthConfig: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '50px'
    },
    {
      field:'caozuo',
      width:'150px'
    },
    {
      field: 'showType',
      width: '150px'
    }
  ];//表格宽度配置
  layoutDirection: FormLayout = FormLayout.Horizontal;
  msgs: { severity: any; summary: any; content: any; }[];
  processId: any;
  constructor(private UserService:UserService,private dialogService:DialogService,private DeviceService:DeviceService,private EncodeRulesService:EncodeRulesService,private ProcessService:ProcessService,private Router:Router,private ActivatedRoute:ActivatedRoute) { }
  ngOnInit(): void {
    this.UserService.GetAllEmploy(1,9999).subscribe((res:any)=>{
      this.user = res.items
     })
     this.DeviceService.GetEquipments(null,null,null,null,'',1,9999).subscribe((res:any)=>{
      this.device = res.items
     })
     this.ActivatedRoute.params.subscribe((params:any)=>{
      const id = params['processId'];
      this.tabActiveId = this.ActivatedRoute.snapshot.queryParamMap.get('tabActiveId');
      this.processId = id;

      this.ProcessService.GetProcessById(id).subscribe((res:any)=>{
        this.Process.processName = res.processName;
        this.Process.processNum = res.processNum;
        this.Process.processNote = res.processNote;
        this.Process.attachmentUrl = res.attachmentUrl;
        if(res.processUsers.length>0){
        this.tableData = res.processUsers.map((item:any)=>{
          return {
            id:item.id,
            employeeCode:item.employeeCode,
            name:item.name,
            ownerPhoneNumber:item.ownerPhoneNumber,
            departmentName:item.departmentName,
          }
        })
      }
      if(res.processEquipments.length>0){
        this.deviceData = res.processEquipments.map((item:any)=>{
          return {
            id:item.equipmentId,
            equipmentName:item.equipmentName,
            equipmentNum:item.equipmentNum,
          }
        })
      }
      })
  })
}
  add(){
    this.tableData.push({
      id:null,
      employeeCode:null,
      name:null,
      ownerPhoneNumber:null,
      departmentName:null,
    })
  }
  addDevice(){
    this.deviceData.push({
      id:null,
      equipmentName:null,
      equipmentNum:null,
    })
  }
  remove(i: number){
    if(this.tableData.length>1){
      this.tableData.splice(i,1);
    }else if(this.tableData.length==1){
      this.tableData = [
        {
          id:null,
          employeeCode:null,
          name:null,
          ownerPhoneNumber:null,
          departmentName:null,
        }
      ]
    }

  }
  removeDevice(i: number){
    if(this.deviceData.length>1){
      this.deviceData.splice(i,1);
    }else if(this.deviceData.length==1){
      this.deviceData = [
        {
          id:null,
          equipmentName:null,
          equipmentNum:null,
        }
      ]
    }
  }
  selectUser(index:number,dialogtype?: string,){
    let data = {
      user:this.user,
      display: false,
      placeholder: '请选择人员'
    };
    const results = this.dialogService.open({
      id: 'department',
      width: '800px',
      title: '人员',
      data:data,
      content: SelectUserComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if(results.modalContentInstance.selectData){
              if (this.tableData.some(item => item.employeeCode === results.modalContentInstance.selectData.employeeCode)) {
                this.showToast('error', '错误', '不能重复选择人员');
              }else{
                this.tableData[index].id = results.modalContentInstance.selectData.id;
                this.tableData[index].employeeCode = results.modalContentInstance.selectData.employeeCode;
                this.tableData[index].name = results.modalContentInstance.selectData.name;
                this.tableData[index].ownerPhoneNumber = results.modalContentInstance.selectData.ownerPhoneNumber;
                this.tableData[index].departmentName = results.modalContentInstance.selectData.departmentName;
              }

              results.modalInstance.hide();
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }//人员信息
  selectDevice(index:number,dialogtype?: string,){
    let data = {
      device:this.device,
      display: false,
      placeholder: '请选择设备'
    };
    const results = this.dialogService.open({
      id: 'department',
      width: '800px',
      title: '设备',
      data:data,
      content: SeleceDeviceComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if(results.modalContentInstance.selectData){
              if(this.deviceData.some(item => item.equipmentNum === results.modalContentInstance.selectData.equipmentNum)) {
                this.showToast('error', '错误', '不能重复选择设备');
              }else{
                this.deviceData[index].id = results.modalContentInstance.selectData.equipmentId;
                this.deviceData[index].equipmentName = results.modalContentInstance.selectData.equipmentName;
                this.deviceData[index].equipmentNum = results.modalContentInstance.selectData.equipmentNum;
              }
              results.modalInstance.hide();
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }//设备信息
  showToast(type: any,summary:any,content:any) {
    switch (type) {
    default:
      this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  submit(){
    this.Process.processUserIds = this.tableData.map(item => item.id).filter(code => code !== null);
    this.Process.processEquipmentIds = this.deviceData.map(item => item.id).filter(num => num !== null);

    this.ProcessService.UpdateProcess(this.processId,this.Process).subscribe((res:any)=>{
      this.showToast('success','成功','工序更新成功')
      setTimeout(() => {
        this.Router.navigate(['/pages/process/process-item'])
      }, 1500);
    },(error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    })
  }
  cancle(){
    this.Router.navigate(['/pages/process/process-item'])
  }
  onButtonClick(dialogtype?:string) {
    const results = this.dialogService.open({
      title: '工序附件',
      width: '800px',
      backdropCloseable: false,
      data: {
        data: '工序附件',
        urls: this.Process.attachmentUrl
      },
      content: AttachmentComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.Process.attachmentUrl = results.modalContentInstance.urls;
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
}
